package com.jack.netty.udp.server;

import com.jack.netty.log.LoggerManager;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

/**
 * Created by jack on 15/12/11.
 */
public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    private UdpServerListener udpServerListener = null;


    public UdpServerHandler(){

    }

    public UdpServerListener getUdpServerListener() {
        return udpServerListener;
    }

    public void setUdpServerListener(UdpServerListener udpServerListener) {
        this.udpServerListener = udpServerListener;
    }

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {

        ByteBuf buf = msg.copy().content();
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        buf.release();
        LoggerManager.getInstance().getiLogger().info(getClass(),"数据长度:"+bytes.length);

        String fromIp = msg.sender().getHostString();
        int fromPort = msg.sender().getPort();
        String clientId = ctx.channel().id().asLongText();

        if(udpServerListener == null){
            LoggerManager.getInstance().getiLogger().error(getClass(),"未设置消息监听器!请检查程序");
        }else{
            if(udpServerListener.isByteMsg()){
                LoggerManager.getInstance().getiLogger().info(getClass(),"收到客户端: "+clientId+" ip: "+fromIp+" port: "+fromPort+" UDP数据:"+bytes);
                try{
                    udpServerListener.messageReceived(fromIp,fromPort,bytes);
                }catch (Exception e){
                    LoggerManager.getInstance().getiLogger().error(getClass(),"消息处理器错误:"+e.getMessage());
                }
            }else{
                String message = new String(bytes,"UTF-8");
                LoggerManager.getInstance().getiLogger().info(getClass(),"收到客户端: "+clientId+" ip: "+fromIp+" port: "+fromPort+" UDP消息:"+message);
                try {
                    udpServerListener.messageReceived(fromIp,fromPort,message);
                }catch (Exception e){
                    LoggerManager.getInstance().getiLogger().error(getClass(),"消息处理器错误:"+e.getMessage());
                }
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LoggerManager.getInstance().getiLogger().error(getClass(),"接受消息错误:"+cause == null ? "" : cause.getMessage());

        if(udpServerListener == null){
            LoggerManager.getInstance().getiLogger().error(getClass(),"未设置消息监听器!请检查程序");
        }else{
            udpServerListener.errorInfo(cause == null ? "" : cause.getMessage());
        }

        if(ctx != null){
            ctx.close();
        }
    }
}
